<template>
    <div class="marketing_coupon_detail">
        <!-- 头部 -->
        <div class="marketing_coupon_detail_top">
            <div class="marketing_coupon_detail_header">
                <div class="marketing_coupon_detail_header_left">
                    <h1>
                        {{ basisInfo.couponName }}
                        <el-tag class="custom-el-tag" :class="`custom-tag-${basisInfo?.couponStatus}`" effect="plain">{{
                            basisInfo?.couponStatusName
                        }}</el-tag>
                    </h1>
                </div>
                <!-- 3已失效 4已过期 5未启用 6已启用 -->
                <div class="marketing_coupon_detail_header_right">
                    <el-button
                        v-if="[6].includes(basisInfo?.couponStatus / 1)"
                        type="primary"
                        :ref="el => setItemRef(el, 'spreadButtonRef')"
                        @click="spreadHandler('spreadButtonRef')"
                        v-auth="'coupon_list:spread'"
                        >推广</el-button
                    >
                    <el-button
                        v-if="[6].includes(basisInfo?.couponStatus / 1)"
                        @click="popoverHandler('disableButtonRef')"
                        v-auth="'coupon_list:invalid'"
                        :ref="el => setItemRef(el, 'disableButtonRef')"
                        >失效</el-button
                    >
                    <el-button
                        v-if="[5].includes(basisInfo?.couponStatus / 1)"
                        @click="popoverHandler('enableButtonRef')"
                        type="primary"
                        v-auth="'coupon_list:enable'"
                        :ref="el => setItemRef(el, 'enableButtonRef')"
                        >启用</el-button
                    >
                    <el-button
                        v-if="[3, 4].includes(basisInfo?.couponStatus / 1)"
                        @click="popoverHandler('removeButtonRef')"
                        v-auth="'coupon_list:remove'"
                        :ref="el => setItemRef(el, 'removeButtonRef')"
                        >删除</el-button
                    >
                </div>
            </div>
            <el-row class="custom-header-row">
                <el-col :span="8"
                    >优惠券类型：<span>{{ basisInfo.couponType == 1 ? '满减券' : '折扣券' }}</span></el-col
                >
                <el-col :span="8"
                    >创建人：<span>{{ basisInfo.creatUserName }}</span></el-col
                >
                <el-col :span="8"
                    >创建时间：<span>{{ basisInfo.createdAt || '-' }}</span></el-col
                >
            </el-row>
        </div>
        <!-- 内容 -->
        <div class="marketing_coupon_detail_content">
            <!-- tab -->
            <el-tabs class="statistics-tab" v-model="tabActiveName">
                <el-tab-pane
                    v-for="{ name, label } in detailTabs"
                    :key="name"
                    :label="label"
                    :name="name"></el-tab-pane>
            </el-tabs>
            <component :is="componentId" :id="id" :info="basisInfo"></component>
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-coupon-popover-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :width="currentRow.ref === 'spreadButtonRef' ? 400 : 240"
            :visible="popoverVisible">
            <div
                class="custom-coupon-popover-class-main"
                v-click-outside="onClickOutside"
                v-if="['disableButtonRef', 'removeButtonRef', 'enableButtonRef'].includes(currentRow.ref)">
                <!-- 启用、失效、删除 -->
                <h3 style="margin-bottom: 16px">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>
                    <!-- 删除 -->
                    <template v-if="currentRow.ref == 'removeButtonRef'"> 确定要删除该优惠券吗？ </template>
                    <!-- 启用 -->
                    <template v-if="currentRow.ref == 'enableButtonRef'"
                        >优惠券启用后将可以领取，确定要启用该优惠券吗？</template
                    >
                    <!-- 失效 -->
                    <template v-if="currentRow.ref == 'disableButtonRef'">
                        优惠券失效后将无法领取，已领取的优惠券不受影响，确定要失效该优惠券吗？
                    </template>
                </h3>
                <div style="text-align: right">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
            <SpreadBox
                v-if="popoverVisible && currentRow.ref === 'spreadButtonRef'"
                :path="path"
                :params="params"
                :downloadName="downloadName"
                :popoverFn="popoverVisibleHandler" />
        </el-popover>
    </div>
</template>

<script setup>
import { ref, unref, nextTick, computed, watch, defineAsyncComponent, onMounted, onUnmounted, reactive } from 'vue';
import request from '@/request/index';
import { useRoute } from 'vue-router';
import { setLayout, resetLayout } from '@/hooks/layout';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import { floatDivide } from '@/commons/utils';
import storage from '@/commons/storage';
import SpreadBox from '@/components/SpreadBox.vue';

const route = useRoute();

let basisInfo = reactive({});
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null, codeUrl: null });
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};

const detailTabs = [
    { name: 'statistics', label: '数据统计' },
    { name: 'group', label: '详情' }
];
const tabActiveName = ref('group');

const queryType = computed(() => route?.query?.type || 'group');
const componentId = computed(() => {
    const defineAsyncComponents = {
        group: defineAsyncComponent(() => import('./group.vue')),
        statistics: defineAsyncComponent(() => import('./statistics.vue'))
    };
    return defineAsyncComponents[tabActiveName.value];
});
const id = computed(() => {
    return route?.query?.id;
});
const query = computed(() => {
    return route?.query;
});

watch(
    () => queryType,
    val => {
        tabActiveName.value = val.value;
    },
    { immediate: true }
);

// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    let method = null;
    let params = null;
    if (currentRow.ref == 'disableButtonRef') {
        // 失效
        method = 'couponExpireServ';
        params = { id: unref(id), couponStatus: 3 };
    } else if (currentRow.ref == 'enableButtonRef') {
        // 启用
        method = 'couponEnable';
        params = { id: unref(id) };
    } else if (currentRow.ref == 'removeButtonRef') {
        // 删除
        method = 'couponDestroy';
        params = { id: [unref(id)] };
    }

    await request(method, params);
    popoverVisibleHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
    if (currentRow.ref === 'removeButtonRef') {
        window.close();
    }
    getBasisInfo();
};

const popoverHandler = ref => {
    buttonRef.value = itemRefs[ref];
    currentRow.ref = ref;

    nextTick(() => {
        popoverVisibleHandler(true);
    });
};

// 推广
let path = ref();
let params = ref();
let downloadName = ref();
const spreadHandler = async ref => {
    path.value = 'pages-user/coupon/receive';
    params.value = `couponId=${basisInfo.couponId}&shopId=${storage.get('ZW-SHOPID')}`;
    downloadName.value = basisInfo.couponName;
    popoverHandler(ref);
};

const getBasisInfo = async () => {
    const { data } = await request('couponDetailServ', { id: unref(id) });
    // data.activityAt = [data.activityStartTime, data.activityEndTime];
    // if (data.couponType == 1) {
    //     data.discountSet.orderAmount = data.discountSet.orderAmount / 100;
    //     data.discountSet.reduce = data.discountSet.reduce / 100;
    // } else {
    //     data.discountSet.reduce = data.discountSet.reduce / 10;
    // }
    const realCoupon = data?.realCoupon || {};
    realCoupon.couponAcquireLimit = realCoupon.couponAcquireLimit || null;
    realCoupon.goods = (realCoupon.goods || [])?.map(item => item.goodsId);
    if ([2].includes(realCoupon.couponPrerequisites / 1)) {
        realCoupon[`couponPrerequisitesAdditional${realCoupon.couponPrerequisites}`] = floatDivide(
            realCoupon.couponPrerequisitesAdditional / 1,
            100
        );
    } else if ([3].includes(realCoupon.couponPrerequisites / 1)) {
        realCoupon[`couponPrerequisitesAdditional${realCoupon.couponPrerequisites}`] =
            realCoupon.couponPrerequisitesAdditional / 1;
    }
    realCoupon.couponDiscountContent = floatDivide(realCoupon.couponDiscountContent, 100);
    realCoupon.couponDiscountMost = realCoupon.couponDiscountMost
        ? floatDivide(realCoupon.couponDiscountMost / 1, 100)
        : null;
    if (realCoupon.couponTimeType == 1) {
        realCoupon.couponTimeAt = [realCoupon.couponTimeStart, realCoupon.couponTimeEnd];
        realCoupon.couponTimeValue = realCoupon.couponTimeValue || null;
        realCoupon.couponReceiveTimeTypeVal = null;
    } else if (realCoupon.couponTimeType == 2) {
        realCoupon.couponReceiveTimeTypeVal = 1;
    } else if (realCoupon.couponTimeType == 3) {
        realCoupon.couponReceiveTimeTypeVal = 2;
        realCoupon.couponTimeType == 2;
    }
    realCoupon.couponAcquireLimitType = realCoupon.couponAcquireLimit ? 2 : 1;

    realCoupon.id = data?.id;
    realCoupon.couponId = data?.couponId;
    realCoupon.couponDiscountMostChecked = !!realCoupon.couponDiscountMost;
    realCoupon.creatUserName = data?.creatUserName || '-';
    Object.assign(basisInfo, realCoupon);
};

const getAllData = async () => {
    getBasisInfo();
};

onMounted(() => {
    getAllData();
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss">
.custom-coupon-popover-class {
    padding: 0px !important;
    &-main {
        padding: 16px !important;
    }
    &-spread {
        padding: 0px !important;
        /* box-shadow: 0px 12px 48px 16px rgba(0, 0, 0, 0.03), 0px 9px 28px 0px rgba(0, 0, 0, 0.05),
            0px 6px 16px -8px rgba(0, 0, 0, 0.08); */
        border-radius: 10px;
        .spread-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 50px;
            border-bottom: 1px solid #eaeaea;
            padding: 0 24px;
            font-size: 16px;
            font-family: PingFangSC-Medium, PingFang SC;
            font-weight: 500;
            color: #33302d;
            &-icon {
                color: #a9a9a9;
                cursor: pointer;
            }
        }
        .custom-preview {
            padding: 24px;
            display: flex;
            flex-direction: column;
            &-radio {
                padding-bottom: 24px;
            }
            &-image {
                width: 140px;
                height: 140px;
            }
            &-title {
                padding: 24px 0 16px;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #33302d;
            }
            &-input {
                .el-input__wrapper {
                    margin-right: 8px;
                    background: #f2f2f2;
                    border-radius: 4px;
                    border: 1px solid #eaeaea;
                    font-size: 14px;
                    font-family: PingFangSC-Regular, PingFang SC;
                    font-weight: 400;
                    color: #33302d;
                    box-shadow: none;
                }
                .el-input-group__append {
                    padding: 0;
                    background: #ffffff;
                    border-radius: 4px;
                    border: 1px solid #ff6b00;
                    box-shadow: none;
                    & > div {
                        padding: 0 12px;
                        cursor: copy;
                        font-size: 14px;
                        font-family: PingFangSC-Regular, PingFang SC;
                        font-weight: 400;
                        color: #ff6b00;
                    }
                }
            }
        }
        .spread-footer {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            height: 54px;
            border-top: 1px solid #eaeaea;
            padding: 0 24px;
        }
        .custom-preview-radio {
            .el-radio-button__inner {
                background: #ffffff;
                border: 1px solid #eaeaea;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #969696;
            }
            .el-radio-button__original-radio:checked + .el-radio-button__inner {
                color: #ff6b00;
                font-weight: 500;
                border: 1px solid #ff6b00;
            }
        }
    }
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        margin-bottom: 10px;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 0 0 16px;
    }

    p + div {
        text-align: right;
    }
}
.custom-coupon-popover-footer {
    text-align: right;
}
</style>
<style lang="scss" scoped>
$colors: #f4f4f4, #fff1ed, #f4f4f4, #f4f4f4, #f4f4f4, #fff1ed;
$colors2: #cccccc, #ff6b00, #33302d, #33302d, #cccccc, #ff6b00;

.marketing_coupon_detail {
    :deep h1 {
        font-weight: 400;
    }
    &_top {
        background-color: #fff;
        margin-bottom: 16px;
        padding: 24px;
    }
    &_header {
        display: flex;
        justify-content: space-between;
        &_left {
            h1 {
                display: flex;
                align-items: center;
                margin: 0;
                font-size: 16px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #33302d;
                .custom-el-tag {
                    margin-left: 8px;
                    cursor: default;
                }
                @for $i from 1 to 7 {
                    .custom-tag-#{$i} {
                        color: nth($colors2, $i);
                        background: nth($colors, $i);
                        border-color: nth($colors, $i);
                        font-size: 14px;
                        font-weight: 400;
                        border-radius: 2px;
                    }
                }
            }

            & > div {
                margin: 20px 0;
                span {
                    color: #9f9f9f;
                    margin-right: 30px;
                }
            }
        }
        &_right .el-button {
            width: 80px;
        }
        margin-bottom: 26px;
    }

    .statistics-tab {
        :deep {
            .el-tabs__item {
                font-size: 16px;
                color: #969696;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                &.is-active {
                    font-weight: 500;
                    color: var(--el-color-primary);
                    font-family: PingFangSC-Medium, PingFang SC;
                }
            }
        }
    }

    .custom-header-row .el-col {
        color: #969696;
        font-size: 14px;
        span {
            color: #33302d;
        }
    }

    &_content {
        background-color: #fff;
        padding: 24px;
        padding-top: 12px;
    }
    :deep .el-tabs__nav-wrap::after {
        height: 1px;
    }
}
</style>
